import 'package:acgn_pioneer/models/comment_model.dart';
import 'package:acgn_pioneer/widgets/reader/_index.dart';
import 'package:event_bus/event_bus.dart';
import 'package:flutter/widgets.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../../../public.dart';
import '../services/_index.dart';
import 'utils.dart';

/// 评论弹窗
class ReaderComment extends StatefulWidget {
  /// 漫画
  final ChapterModel chapterModel;

  // 是否是漫画主体评论
  final bool isComicType;

  ReaderComment({Key key, this.chapterModel, this.isComicType = false})
      : super(key: key);

  @override
  ReaderCommentState createState() => new ReaderCommentState();
}

class ReaderCommentState extends State<ReaderComment> {
  List<CommentModel> listAll = [];
  int totalCount = -1;
  ReaderCommentService readerCommentService = ReaderCommentService();
  Color gray = ColorUtil.rgba(255, 255, 255, 0.6);
  int loadingType = 1; // 1：热门、2：最新、3：更多
  int cliType = 1; // 1：热门、2：最新
  bool hasInited = false; // 是否初始化完成
  bool hasMore = false; // 是否有更多评论【用于显示更多评论按钮】
  bool hasCliMore = false;
  bool hasMoreData = false; // 是否有更多加载帖子
  int page = 1; // 当前页码
  int pageSize = 20;
  bool isComicType = false;
  List<CommentModel> lstFirstWater = [];
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  EventBus event = EventBus();

  @override
  void initState() {
    super.initState();

    isComicType = widget.isComicType;

    doRequest();
    getCommentCount();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        color: Color(0xff1B1B26),
        padding: EdgeInsets.only(top: 28),
        child: DefaultTextStyle.merge(
            style: TextStyle(color: Colors.white),
            child: Column(
              children: [
                Expanded(
                    child: Container(
                        padding: EdgeInsets.only(left: 16, right: 16),
                        child: Column(
                          children: [
                            Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Container(
                                      constraints:
                                          BoxConstraints(maxWidth: 240),
                                      child: Text(
                                        isComicType
                                            ? '《${widget.chapterModel.comicModel.name}》'
                                            : widget.chapterModel.name,
                                        style: TextStyle(fontSize: 18),
                                        overflow: TextOverflow.ellipsis,
                                      )),
                                  isComicType
                                      ? SizedBox.shrink()
                                      : GestureDetector(
                                          onTap: () {
                                            isComicType = true;
                                            cliType = 1;
                                            resetRequestData();
                                            getCommentCount();
                                            getList();
                                          },
                                          child: Row(
                                            children: [
                                              Text(
                                                '漫画评论',
                                                style: TextStyle(
                                                    color: gray, fontSize: 14),
                                              ),
                                              SVG.icon('arrow_right',
                                                  color: gray, size: 12)
                                            ],
                                          ),
                                        )
                                ]),
                            SizedBox(height: 18),
                            ReaderCommentTitle(
                              comicModel: widget.chapterModel.comicModel,
                              totalCount: totalCount,
                              showSwitch: !isComicType,
                              isComicType: isComicType,
                              cliType: cliType,
                              onTap: (int type) {
                                cliType = type;
                                resetRequestData();
                                setState(() {});
                                getList();
                              },
                            ),
                            hasInited && totalCount == 0
                                ? EmptyComponent(
                                    desc: '暂无评论',
                                    imageAsset: 'assets/images/empty_huifu.png')
                                : buildContent(),
                          ],
                        ))),
                CommentUtil.buildInput(
                    placeholder: '评论点赞，都要勇往直前~',
                    onTap: () {
                      CommentUtil.showInput(
                          context,
                          (context) => PopInputBoxComponent(
                                  child: ReaderCommentInput(
                                chapterModel: widget.chapterModel,
                                isComicType: isComicType,
                                placeholder: '评论点赞，都要勇往直前~',
                              )));
                    })
              ],
            )));
  }

  buildContent() {
    if (!hasInited) {
      return Container(height: 400, child: LoadingComponent());
    }
    return Container(
        margin: EdgeInsets.only(top: 10),
        height: 420,
        child: buildView(ListView.builder(
            physics: ClampingScrollPhysics(),
            shrinkWrap: true,
            itemCount: listAll.length,
            itemBuilder: (context, index) {
              return buildItem(index);
            })));
  }

  buildItem(int index) {
    if (index == listAll.length - 1 && hasMore && !hasCliMore) {
      return Column(
        children: [
          buildReaderCommentItem(index),
          SizedBox(height: 10),
          GestureDetector(
            onTap: () {
              if (hasCliMore) {
                return;
              }
              hasCliMore = true;
              listAll.addAll(lstFirstWater);
              if (lstFirstWater.length != pageSize) {
                _refreshController.loadNoData();
              }
              setState(() {});
            },
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Text(
                  '更多评论',
                  style: TextStyle(color: gray, fontSize: 14),
                ),
                SizedBox(width: 2),
                SVG.icon('arrow_down', color: gray, size: 14)
              ],
            ),
          )
        ],
      );
    }
    return buildReaderCommentItem(index);
  }

  buildReaderCommentItem(int index) {
    return ReaderCommentItem(
      commentModel: listAll[index],
      chapterModel: widget.chapterModel,
      comicModel: widget.chapterModel.comicModel,
    );
  }

  Widget buildView(Widget widget) {
    return RefreshConfig(
        child: SmartRefresher(
            enablePullDown: true,
            enablePullUp: true,
            controller: _refreshController,
            onRefresh: _onRefresh,
            onLoading: _onLoading,
            footer: CustomFooter(builder: buildFooter),
            child: widget));
  }

  Widget buildFooter(BuildContext context, LoadStatus mode) {
    if (mode == LoadStatus.loading) {
      return LoadingComponent();
    }
    return SizedBox.shrink();
  }

  void _onRefresh() async {
    resetRequestData();
    await doRequest();
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    page++;
    await doRequest();
  }

  doRequest() async {
    await getList();
    // 非水贴的没有数据
    if ((loadingType != 3 && !hasMore) && !hasMoreData) {
      _refreshController.loadNoData();
      return;
    }
    //水贴没有数据
    if (!hasMoreData) {
      _refreshController.loadNoData();
      return;
    }
    _refreshController.loadComplete();
  }

  // 获取评论总数
  getCommentCount() async {
    var chapter = widget.chapterModel;
    totalCount = await readerCommentService.getNewCommentCount(
        chapter.comicModel.id, isComicType ? 0 : chapter.id);
    setState(() {});
  }

  getList() async {
    switch (loadingType) {
      case 1:
        await getHotComments();
        break;
      case 2:
        await getNormalComments(isWater: false);
        break;
      case 3:
        await getNormalComments();
        break;
    }
    if (!hasInited) {
      // 设置初始化完成标志
      hasInited = true;
    }
  }

  // 重置请求相关状态
  resetRequestData() {
    page = 1;
    hasMore = false;
    hasCliMore = false;
    hasMoreData = false;
    hasInited = false;
    loadingType = cliType;
    listAll.clear();
  }

  // 获取热门评论
  getHotComments() async {
    var temps = await readerCommentService.getHotComment(
      page,
      widget.chapterModel.comicModel.id,
      !isComicType ? widget.chapterModel.id : 0,
    );
    if (temps.length > 0) {
      listAll.addAll(temps);
      await getChildrenComments(temps, false);
    }
    hasMoreData = temps.length == pageSize; // 请求数量一致，说明还有数据

    // 请求条数不满整页，表明没有当前数据了，自动切换到水贴请求
    if (temps.length < pageSize) {
      loadingType = 2;
      page = 1;
      await getNormalComments(isFirst: true);
    }
    setState(() {});
  }

  // 获取普通评论
  getNormalComments({bool isFirst = false, bool isWater = true}) async {
    var temps = await readerCommentService.getNormalComment(
        page,
        widget.chapterModel.comicModel.id,
        !isComicType ? widget.chapterModel.id : 0,
        isWater: isWater);
    if (temps.length == 0) {
      return;
    }
    hasMoreData = temps.length == pageSize; // 请求数量一致，说明还有数据
    if (isFirst && isWater) {
      // 如果是第一页水贴，先进行缓存，点击更多评论时在加入主列表
      hasMore = true;
      lstFirstWater = temps;
    } else {
      listAll.addAll(temps);
    }

    await getChildrenComments(temps, isFirst);
    if (!isFirst) {
      setState(() {});
    }
  }

  // 获取组装子评论
  getChildrenComments(List<CommentModel> lst, bool isFirst) async {
    var ids = lst.map((e) => e.id).join(',');
    List<CommentModel> temps =
        await readerCommentService.getChildrenComment(ids);
    var tempAll = isFirst ? lstFirstWater : listAll;
    temps.forEach((temp) {
      var model = tempAll.firstWhere((item) => item.id == temp.fatherId);
      model.lstChildren.add(temp);
    });
  }
}
